package org.iabako.server.controller.timer.logtrack;

import org.apache.log4j.Logger;
import org.iabako.server.dao.support.LogExceptionDAO;
import org.iabako.server.tools.ServerTools;
import org.iabako.shared.entity.support.LogException;
import org.iabako.shared.tools.GenericTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.List;

/**
 * Created by jose on 24/05/15.
 */

@Controller
public class ErrorLogTrackController {

    static Logger log = Logger.getLogger(ActivityLogTrackController.class.getName());

    @Autowired
    private LogExceptionDAO logExceptionDAO;

    public String trackErrorLogs() {
        log.info("Executing ErrorLogTrackController...");

        ServerTools serverTools = new ServerTools();
        Date yesterday = serverTools.addDaysToDate(serverTools.resetTime(new Date()), -1);

        List<LogException> logExceptionList = logExceptionDAO.getExceptionByDate(yesterday);
        StringBuilder result = new StringBuilder();
        StringBuilder logs = new StringBuilder();

        for (LogException log : logExceptionList) {
            logs.append(GenericTools.formatTime(log.getDate()) + " : " + log.getUserEmail() + " : " + log.getException() + "\n\n");
        }
        if (logs.length() > 0) {
            result.append("Dear Admin,\nThis is the error tracking log of " + GenericTools.formatDate(yesterday) + " : \n\n");
            result.append(logs);
        }
        return result.toString();
    }
}
